<template>
  <div class="amap">
    <!-- 导航栏 -->
    <van-nav-bar title="详细地址" left-arrow :z-index="999" fixed @click-left="close" />

  </div>
</template>

<script>
import areaSelect from 'components/areaSelect'

export default {
  name: 'AmapSelect',
  components: {
    areaSelect
  },
  props: {
    initAmap: {
      type: Boolean,
      default: false
    },
    dataModel: {
      type: Object,
      default: {}
    },
    clientWidth: {
      type: Number,
      default: document.body.clientWidth
    }
  },
  data() {
    return {

    }
  },
  watch: {
    initAmap(newVal, oldVal) {
      if (newVal) {
        this.initMap()
      }
    },
    'dataModel.area.value'(newVal, oldVal) {
      if (this.initAmap) {
        this.searchByStationName(newVal.replace(/-/g, '') + this.dataModel.address.value)
      }
    },
    'dataModel.address.value'(newVal, oldVal) {
      if (this.initAmap && newVal != '') {
        this.searchByStationName(this.dataModel.area.value.replace(/-/g, '') + newVal)
      }
    }
  },
  mounted() {
    // this.initMap();
  },
  methods: {
    close() {
      this.$emit('closeAmap')
    },
    closeAreaSelect() {
      this.AreaSelect = false
    },
    // 选择城市的回调
    selCity(item) {
      // console.log(item);
      const self = this
      if (this.locationCity.CityId != item.Id) {
        // this.locationCity = JSON.parse(JSON.stringify(item));
        this.searchPlace.setCity(item.Name ? item.Name : item.SortName)
        // 根据城市名称正向地理编码
        this.$geocoder.getLocation(item.Name ? item.Name : item.SortName, (status, result) => {
          // console.log(result);
          if (status === 'complete' && result.info === 'OK') {
            // result中对应详细地理坐标信息
            self.map.setZoom(15)
            self.map.setCenter([result.geocodes[0].location.lng, result.geocodes[0].location.lat])
          }
        })
      }
    },
    getCurrentPosition() {
      // 定位
      this.currentCity.SortName = '定位中...'
      this.$geolocation.getCurrentPosition()
    },
    searchByStationName(keyword) {
      const placeSearch = new AMap.PlaceSearch()
      const self = this
      placeSearch.search(keyword, function(status, result) {
        // 查询成功时，result即对应匹配的POI信息
        if (status === 'complete' && result.info === 'OK') {
          // console.log(result);
          self.dataModel.Lng.value = result.poiList.pois[0].location.lng
          self.dataModel.Lat.value = result.poiList.pois[0].location.lat
          self.map.setCenter([result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat])
        }
      })
    },
    // 初始化地图
    initMap() {
      const self = this
      this.map = new AMap.Map('areaContainer', {
        resizeEnable: true,
        showIndoorMap: true,
        // center: [this.dataModel.Lng.value, this.dataModel.Lat.value],
        zoom: 15,
        // 地图是否可拖动
        dragEnable: true,
        animateEnable: false
      })
      this.map.addControl(this.$geolocation)
      AMap.event.addListener(this.$geolocation, 'complete', this.onComplete)
      AMap.event.addListener(this.$geolocation, 'error', this.onError)
      if (this.dataModel.Lng.value == 0 || this.dataModel.Lat.value == 0) {
        this.getCurrentPosition()
      } else {
        this.map.setCenter([this.dataModel.Lng.value, this.dataModel.Lat.value])
        this.map.getCity(result => {
          // console.log(result);
          self.currentCity.SortName = result.city ? result.city : result.province
        })
      }
      this.mapPoint = this.map.getCenter()
      // 调用高德地图UI插件
      AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
        self.positionPicker = new PositionPicker({
          mode: 'dragMap', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: self.map,
          iconStyle: {
            // 自定义外观
            url: require('@/assets/images/location-ding.png'), // 图片地址
            size: [20, 40], // 要显示的点大小，将缩放图片
            ancher: [10, 40] // 锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
          }
        })
        self.positionPicker.start()
        self.positionPicker.on('success', result => {
          // console.log(result);
          if (result.info == 'OK') {
            self.locationCity.ProvinceId = parseInt(result.regeocode.addressComponent.adcode.substr(0, 2) + '0000')
            self.locationCity.ProvinceName = result.regeocode.addressComponent.province
            self.locationCity.CityId = parseInt(result.regeocode.addressComponent.adcode.substr(0, 4) + '00')
            self.locationCity.CityName = result.regeocode.addressComponent.city
              ? result.regeocode.addressComponent.city
              : result.regeocode.addressComponent.province
            self.locationCity.AreaId = parseInt(result.regeocode.addressComponent.adcode)
            self.locationCity.AreaName = result.regeocode.addressComponent.district
            self.searchPlace.setCity(self.locationCity.CityName)
            if (self.isPositionPicker) {
              self.mapPoint = result.position
              const lastIndexOf = result.address.lastIndexOf(result.regeocode.addressComponent.district)
              self.isSearch = false
              self.nearSearch.setPageIndex(1)
              self.currentPosition(
                result.regeocode.formattedAddress.substring(lastIndexOf + result.regeocode.addressComponent.district.length)
              )
            } else {
              self.isPositionPicker = true
            }
          } else {
            self.finished = true
          }
        })
      })
    },
    // 定位成功
    onComplete(data) {
      // console.log(data);
      this.currentCity.SortName = data.addressComponent.city ? data.addressComponent.city : data.addressComponent.province
      this.currentCity.Id = data.addressComponent.adcode.substr(0, 4) + '00'
    },
    // 定位失败
    onError(data) {
      // console.log(data);
      this.$toast.fail({
        message: '获取当前定位信息失败，请刷新',
        icon: 'close'
      })
    },
    // 当前位置
    currentPosition(positonName) {
      this.loading = true
      this.finished = false
      this.addressList.length = 0
      this.address = 0
      this.addressList.push({
        name: positonName,
        address: '[位置]',
        position: this.mapPoint,
        distance: ''
      })
      this.searchNear()
    },
    // 附近地点
    searchNear() {
      const self = this
      // 第一个参数是关键字，这里传入的空表示不需要根据关键字过滤
      // 第二个参数是经纬度，数组类型
      // 第三个参数是半径，周边的范围
      // 第四个参数为回调函数
      self.nearSearch.searchNearBy('', [self.mapPoint ? self.mapPoint.lng : 0, self.mapPoint ? self.mapPoint.lat : 0], 30000, function(
        status,
        result
      ) {
        // console.log(result);
        self.loading = false
        if (result.info === 'OK') {
          for (let i = 0, len = result.poiList.pois.length; i < len; i++) {
            self.addressList.push({
              name: result.poiList.pois[i].name,
              address: result.poiList.pois[i].address,
              position: result.poiList.pois[i].location,
              distance: result.poiList.pois[i].distance
                ? result.poiList.pois[i].distance < 1000
                  ? result.poiList.pois[i].distance + 'm|'
                  : (result.poiList.pois[i].distance / 1000).toFixed(1) + 'km|'
                : ''
            })
          }
          // console.log(self.addressList);
          self.nearSearch.setPageIndex(self.nearSearch.L.pageIndex + 1)
        } else {
          // self.$toast("获取周边位置信息失败，请刷新重试！");
          self.finished = true
        }
      })
    },
    // 搜索地点
    searchPlaceFn(key) {
      if (key.trim()) {
        this.isSearch = true
        this.loading = true
        this.finished = false
        this.searchPlace.setPageIndex(1)
        this.addressList.length = 0
        this.address = -1
        this.moreSearchPlace(key)
      } else {
        this.$toast('请输入搜索关键词')
      }
    },
    // 更多搜索地点
    moreSearchPlace(key) {
      const self = this
      self.searchPlace.search(key, function(status, result) {
        // console.log(result);
        self.loading = false
        if (result.info === 'OK') {
          for (let i = 0, len = result.poiList.pois.length; i < len; i++) {
            self.addressList.push({
              name: result.poiList.pois[i].name,
              address: result.poiList.pois[i].address,
              position: result.poiList.pois[i].location,
              distance: result.poiList.pois[i].distance
                ? result.poiList.pois[i].distance < 1000
                  ? result.poiList.pois[i].distance + 'm|'
                  : (result.poiList.pois[i].distance / 1000).toFixed(1) + 'km|'
                : ''
            })
          }
          self.searchPlace.setPageIndex(self.searchPlace.L.pageIndex + 1)
        } else {
          self.finished = true
        }
      })
    },
    // 加载更多地点
    onLoad() {
      if (this.isSearch) {
        this.moreSearchPlace(this.searchValue)
      } else {
        this.searchNear()
      }
    },
    // 选择定位地址
    selPosition(item, index) {
      if (this.address != index) {
        // console.log(item);
        this.isPositionPicker = false
        this.address = index
        this.mapPoint = item.position
        this.map.setCenter([this.mapPoint.lng, this.mapPoint.lat])
      }
    },
    submit() {
      const self = this
      // console.log(self.locationCity);
      self.dataModel.area.value = self.locationCity.ProvinceName + '-' + self.locationCity.CityName + '-' + self.locationCity.AreaName
      self.dataModel.area.ProvinceId = self.locationCity.ProvinceId
      self.dataModel.area.ProvinceName = self.locationCity.ProvinceName
      self.dataModel.area.CityId = self.locationCity.CityId
      self.dataModel.area.CityName = self.locationCity.CityName
      self.dataModel.area.AreaId = self.locationCity.AreaId
      self.dataModel.area.AreaName = self.locationCity.AreaName
      self.dataModel.address.value = self.addressList[self.address].name
      self.dataModel.Lng.value = self.mapPoint.lng
      self.dataModel.Lat.value = self.mapPoint.lat
      self.$emit('confirmAmap', self.dataModel)
      self.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.amap {
  max-width: 10rem;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 3000;
  background: #f5f5f5;
  overflow-y: scroll;
}
#areaContainer {
  width: 750px;
  height: 400px;
  position: fixed;
  top: 200px;
  z-index: 2000;
}
</style>
